package cn.rengy.web.framework.sql;

import java.util.List;

import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import cn.rengy.tool.core.GenericTokenParser;
import cn.rengy.tool.core.TokenHandler;
/**
 * 解析${name=:x} x是否有值，有返回 name=:x 否则返回 空字符串
 * @author rengy
 *
 */
public class MapSqlParameterHandler implements TokenHandler{

	private  SqlParameterSource sqlParameterSource;
	
	public MapSqlParameterHandler(SqlParameterSource sqlParameterSource) {
		this.sqlParameterSource=sqlParameterSource;
	}
	@Override
	public String handleToken(String content) {
		_ParsedSql parsedSql=_NamedParameterUtils.parseSqlStatement(content);
		List<String> names=parsedSql.getParameterNames();
		boolean isContains=true;
		if(!names.isEmpty()) {
			for(String name:names) {
				Object paramValue=sqlParameterSource.getValue(name);
				if(paramValue==null||paramValue.toString().length()==0) {
					isContains=false;
					break;
				}
			}
		}
		if(isContains) {
			int start  = content.indexOf("#");
			if(start > -1) {
			    GenericTokenParser parser = new GenericTokenParser("#", "#", new SqlVariablesHandler(sqlParameterSource));
			    content=parser.parse(content);
			}
			return content;
		}else {
			return "";
		}
	}

}
